﻿using System;
using System.Collections.Generic;
using System.Data.Common;

namespace Accumulation.Database {
    /// <summary>
    /// 事务对象缓存类
    /// </summary>
    /// <typeparam name="TConnection">具体 Connection 类型</typeparam>
    /// <typeparam name="TTransaction">具体 Transaction 类型</typeparam>
    internal class DbTransactions<TConnection, TTransaction>
        where TConnection : DbConnection, new()
        where TTransaction : DbTransaction {
        // connection 对象实例
        private TConnection _cacheConnection;
        private Dictionary<Guid, TTransaction> _cacheTransaction =
            new Dictionary<Guid, TTransaction>();

        /// <summary>
        /// 事务关联的 Conneciton 对象
        /// </summary>
        /// <returns>Conneciton</returns>
        public TConnection ConnectionObject() {
            return this._cacheConnection;
        }
        /// <summary>
        /// 开始一个事务，并返回一个事务缓存字典的 key
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <returns>事务缓存字典的 key</returns>
        public Guid BeginTransaction(string connectionString) {
            this._cacheConnection = new TConnection();
            this._cacheConnection.ConnectionString = connectionString;
            this._cacheConnection.Open();
            TTransaction trans = (TTransaction)this._cacheConnection.BeginTransaction();
            Guid guid = Guid.NewGuid();
            this._cacheTransaction.Add(guid, trans);
            return guid;
        }
        /// <summary>
        /// 提交一个事务
        /// </summary>
        /// <param name="guid">事务缓存字典的 key</param>
        public void CommitTransaction(Guid guid) {
            this._cacheTransaction[guid].Commit();
            this._cacheConnection.Close();
            this._cacheConnection.Dispose();
        }
        /// <summary>
        /// 回滚一个事务
        /// </summary>
        /// <param name="guid">事务缓存字典的 key</param>
        public void RollbackTransaction(Guid guid) {
            this._cacheTransaction[guid].Rollback();
            this._cacheConnection.Close();
            this._cacheConnection.Dispose();
        }
        /// <summary>
        /// 返回一个事务缓存字典的 key的事务对象
        /// </summary>
        /// <param name="guid">事务缓存字典的 key</param>
        /// <returns>事务对象</returns>
        public TTransaction Transaction(Guid guid) {
            return this._cacheTransaction[guid];
        }
    }
}
